<template>
  <div class="bg" >
    <div class="container">
      <div style="font-size: 20px; font-weight: bold;text-align: center ;color: rgb(95, 100, 102);line-height: 80px;">用户登录</div>
      <div style="align-items: center;padding: 0 40px;">
      <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" status-icon :rules="rules"
              label-width="auto" class="demo-ruleForm" >
              <el-form-item label="用户名" prop="user_name">
                  <el-input v-model="ruleForm.user_name"  placeholder="请输入用户名"/>
              </el-form-item>
              <el-form-item label="密码" prop="password" >
                  <el-input v-model="ruleForm.password"  type="password" placeholder="请输入密码"  show-password ></el-input>
              </el-form-item>
              <el-form-item label="验证码" prop="code">
                  <el-input v-model="ruleForm.code"  style="width: 150px;" placeholder="请输入验证码"></el-input> 
                  <el-tag  style="height: 32px;width: 50px; margin:0 5px;cursor:pointer;">{{  ruleForm.cCode}}</el-tag>
                  <el-link type="primary" @click="getCode" style="direction: none;">换一张</el-link>
              </el-form-item>   
              <el-checkbox  class="RememberPassword‌" v-model="RememberMe">记住密码</el-checkbox>
      </el-form>
              <br>
      <div style="padding: 0 70px;" > 
          <div style="float: left;" ><el-button type="primary" @click="Login(ruleFormRef)">登 录</el-button></div>
          <div style="float: right;" ><el-button @click="reset(ruleFormRef)">重 置</el-button></div>
      </div>
      <div style="margin-top: 60px; padding: 0 20px;" >
          <div style="float: left;">还没有账号，请 <a style="color: #1a2ee6;text-decoration: none;" href="http://localhost:3000/register">注册</a></div>
          <div style="float: right;"><a style="color: #1a2ee6;text-decoration: none;" href="http://localhost:3000/forgetpwd">忘记密码？</a></div>
      </div>
      </div>
    </div>
  </div>
  </template>
  
  <script lang="ts" setup>
  import { reactive, ref ,onMounted} from 'vue'
  import type { FormInstance, FormRules } from 'element-plus'
  import{loginApi} from '../utils/api/login'
  import {Encrypt} from '../utils/aes'
  //pinia
	import {useUserStore} from '../stores/user'
  	//路由
	import {useRouter} from 'vue-router'
  import{ElMessage}from 'element-plus'

	const router = useRouter();
  const userStore = useUserStore();
  const ruleFormRef = ref<FormInstance>();
  const RememberMe = ref(false);
  const ruleForm = reactive({
    user_name: '',
    password: '',
    code:'',
    cCode:''
  })
  // 表单校验规则
  const checkUserName = (rule: any, value: any, callback: any) => {
          if (value.trim() === '') {
              callback(new Error("用户名不可为空"))
          } else {
              return callback();
          }}
    
  const validatePass = (rule: any, value: any, callback: any) => {
  if (value.trim() === '') {
      callback(new Error("密码不可为空"))
  } else {
      return callback();
  }}
  
  const validateCode=(rule: any, value: any, callback: any)=>{
    if(value.trim()!=ruleForm.cCode){
      ElMessage.error("验证码有误，请重新输入")
    }else{
      return callback();
    }
  }

  const rules = reactive<FormRules<typeof ruleForm>>({
    user_name: [{required: true, message: '请输入3-20位用户名', trigger: 'blur'},
              {
                  min: 3,
                  max: 20,
                  message: '请输入3-20位用户名',
                  trigger: 'blur'
              },
              {
                  validator: checkUserName,
                  trigger: 'blur'}
                ],
    password: [{required: true, message: '请输入8-16位密码', trigger: 'blur'},
              {
                  min: 8,
                  max: 16,
                  message: '请输入8-16位密码',
                  trigger: 'blur'
              },
              {
                  validator: validatePass,
                  trigger: 'blur'}],
    code: [{required: true, message: '请输入验证码', trigger: 'blur'},
              {
                  min: 4,
                  max: 4,
                  message: '请输入4位密码',
                  trigger: 'blur'
              },
              {
                  validator: validateCode,
                  trigger: 'blur'}],
  })
  
  // 生命周期函数
  onMounted(() => {
  getCode();
  const savedCredentials = localStorage.getItem('credentials');
  if (savedCredentials) {
    const { user_name, password } = JSON.parse(savedCredentials);
    ruleForm.user_name = user_name;
    ruleForm.password = password;
    RememberMe.value= true;
  }
  })
  const getCode=()=>{
      let codeString =
        "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
      let codeArray = codeString.split("");
      let num = codeArray.length;
      let newCodeArray = [];
      for (let i = 0; i < 4; i++) {
        let index = Math.floor(Math.random() * num);
        newCodeArray.push(codeArray[index]); //下划线无需理会
      }
       ruleForm.cCode=newCodeArray.join("");
    }

  const Login = (formEl: FormInstance | undefined) => { 
    if (RememberMe.value) {
    localStorage.setItem('credentials', JSON.stringify(ruleForm));
    } else {
    localStorage.removeItem('credentials');
    }
    if (!formEl) return
    formEl.validate((valid) => {
      if (valid) {
        // 登录请求
          loginApi({
					user_name: ruleForm.user_name, 
					password: ruleForm.password
				}).then((res:{code:string;message:any})=> {
          if(res.code !="0"){
             ElMessage.error(res.message)
          }else{
            // 登录成功
          userStore.setToken(res.result.token)//这个红色下划线不用管 不影响运行
          ElMessage({
               message: res.message,
               type: 'success',
           })
          router.push('/home')
          }
				}).catch(error=>{
          ElMessage.error(error.response.data.message)
        })
      }else{
        ElMessage.error("请输入正确格式")
      }
    })
   
  }
  
  const reset = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
  }
  </script>
  
  <style scoped>
     .bg{
      margin: 0; 
      padding: 0; 
      width: 100%; 
      height: 100vh; 
      background-image:  url('../assets/img/BG.png'); 
      background-size: cover; 
      background-repeat: no-repeat; 
      background-position: center; 
      }
      .container {
          width: 400px;
          height: 400px;
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          background-color: #fdffff;
          border-radius: 10px;

      }
      .RememberPassword‌{
        margin-left: 60px;
      }

  </style>